package fafu.comedu.workerrepair;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.security.auth.login.LoginException;

import fafu.comedu.workerrepair.Tool.VerificationSeekBar;
import fafu.comedu.workerrepair.command.Dictionary;
import fafu.comedu.workerrepair.command.LocalDataStream;
import fafu.comedu.workerrepair.command.ReJsonRsp;
import fafu.comedu.workerrepair.entitys.Worker;
import fafu.comedu.workerrepair.entitys.WorkerRegister;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Register extends AppCompatActivity {
    private EditText re_name;
    private EditText re_phone;
    private EditText re_pwd;
    private EditText re_pwd2;
    private EditText re_msg;
    private Button register_login;
    private ProgressDialog pd;
    private String pdTitle;
    private String pdMsg;
    private String msg = "";
    private int showToast = 1;
    private int showPd = 2;
    private int dismissPD = 3;
    private int login_msg = 4;
    private int clean=6;
    private VerificationSeekBar seekBar;
    private Boolean willdo = true;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == showToast)
                showToast();
            else if (msg.what == showPd)
                showPD();
            else if (msg.what == dismissPD)
                dismissPD();
            else if (msg.what == login_msg)
                attend();
            else if (msg.what == clean)
                clean();
        }
    };

    private void clean(){
        seekBar.setProgress(0);
        seekBar.setIndex(100);
        re_pwd.setText("");
        re_pwd2.setText("");
        Message message = new Message();
        message.what = dismissPD;
        handler.sendMessage(message);
        willdo = true;
    }

    private void attend() {
        Intent intent = new Intent(Register.this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        Register.this.finish();
    }

    private  void showPD(){
        pd= ProgressDialog.show(this, pdTitle, pdMsg);
    }
    private  void showPD(String pdTitle,String pdMsg){
        pd= ProgressDialog.show(this, pdTitle, pdMsg);
    }
    private void dismissPD(){
        pd.dismiss();
    }
    private void showToast(){
        Toast toast = Toast.makeText(Register.this, msg, Toast.LENGTH_LONG);
        toast.show();
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        re_name = findViewById(R.id.register_name);
        re_phone = findViewById(R.id.register_phone);
        re_pwd = findViewById(R.id.register_pwd);
        re_pwd2 = findViewById(R.id.register_pwd_sure);
        re_msg = findViewById(R.id.register_msg);
        seekBar = findViewById(R.id.register_seekBar);
        register_login = findViewById(R.id.register_login);
        register_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Register.this,LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                Register.this.finish();
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar1, int progress, boolean fromUser) {
                int ind = seekBar.getProgress();
                if(willdo &&ind >=95){
                    willdo =false;
                    showPD("注册ing","注册信息受理中");
                    register();
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar1) {
//                Log.i("seekBar", "onStopTrackingTouch: start");

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar1) {
                seekBar.setProgress(0);
                seekBar.setIndex(100);
            }
        });
    }
    private boolean isNull(String s){
        if(s==null ||s.trim().equals(""))
            return true;
        return false;
    }
    private void register() {

        String msg = "";
        if(isNull(re_name.getText().toString()))
            msg="名字为空";
        if(isNull(re_pwd.getText().toString()))
            msg="密码为空";
        if(!re_pwd.getText().toString().equals(re_pwd2.getText().toString()))
            msg ="两次输入的密码不一致";
        if(isNull(re_phone.getText().toString()))
            msg="手机号为空";
        if(isNull(re_msg.getText().toString()))
            msg="介绍为空";
        if(!msg.equals("")){
            Toast toast =Toast.makeText(this,msg,Toast.LENGTH_LONG);
            toast.show();
            seekBar.setProgress(0);
            seekBar.setIndex(100);
            re_pwd.setText("");
            re_pwd2.setText("");
            Message message = new Message();
            message.what = dismissPD;
            handler.sendMessage(message);
            willdo = true;
            return ;
        }
        Log.i("register", "register: "+"register");
        Runnable runnable =new Runnable() {
            @Override
            public void run() {
                registerr();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

    }
    private Boolean login() { //将用户信息持久化
        try {
            FileOutputStream out = openFileOutput("data", Context.MODE_PRIVATE);
            String idenstr = re_phone.getText().toString();
            String pwdstr = re_pwd.getText().toString();
            OkHttpClient okHttpClient = new OkHttpClient();
            Log.i("login", "login: "+Dictionary.url.head + "appwork/worlogin?workerId=" + idenstr + "&password=" + pwdstr);
            final Request request = new Request.Builder()
                    .url(Dictionary.url.head + "appwork/worlogin?workerId=" + idenstr + "&password=" + pwdstr)
                    .get()
                    .build();
            Response response = null;
            try {
                response = okHttpClient.newCall(request).execute();
                String json = response.body().string();
                Log.i("login", "login: "+json);
                ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                Integer code = reJsonRsp.getCode();
                if (code.equals(0)) {
                    JSONObject jsonObject = (JSONObject) reJsonRsp.getData();
                    Integer workerId = (Integer) jsonObject.get("id");
                    String name = (String) jsonObject.get("name");
                    Integer isused = (Integer) jsonObject.get("isused");
                    String imgurl = (String) jsonObject.get("imgurl");
                    Integer area = (Integer) jsonObject.get("area");
                    String str = workerId + "_" + idenstr + "_" + pwdstr+"_"+isused+"_"+imgurl+"_"+name+"_"+area;
                    LocalDataStream.writer(str, out);
                    msg = reJsonRsp.getMsg();
                    Message message = new Message();
                    message.what=login_msg;
                    handler.sendMessage(message);
                    return true;
                }
                msg = reJsonRsp.getMsg();
                Message message = new Message();
                message.what=showToast;
                handler.sendMessage(message);
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return  false;
        }
    }
    private Boolean registerr(){
        WorkerRegister worker = new WorkerRegister();
        worker.setName(re_name.getText().toString());
        worker.setPhone(re_phone.getText().toString());
        worker.setPassword(re_pwd.getText().toString());
        worker.setWork(re_msg.getText().toString());
        String json = JSON.toJSONString(worker);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody =RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
        Request request = new Request.Builder()
                .url(Dictionary.url.head+"appwork/register")
                .post(requestBody)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
//                            Log.i("apply repair", "run: "+response.body().string());
            json = response.body().string();
            System.out.println(json);
            ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
            Integer code = reJsonRsp.getCode();
            if(!code.equals(0)) {
                msg = reJsonRsp.getMsg();
                Message cl = new Message();
                cl.what=clean;
                handler.sendMessage(cl);
                Message message = new Message();
                message.what=showToast;
                handler.sendMessage(message);
                return false;
            }
            else {
                msg = "注册成功";
            }
            Message message = new Message();
            message.what=showToast;
            handler.sendMessage(message);
            if(code.equals(0)) {
                message = new Message();
                message.what = dismissPD;
                handler.sendMessage(message);
                pdTitle = "登录";
                pdMsg = "正在发送登录请求";
                message = new Message();
                message.what = showToast;
                handler.sendMessage(message);
                login();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}
